package com.zzh.myapplication.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import net.icarplus.car.R;
import net.icarplus.car.app.MyApplication;
import net.icarplus.car.bean.AcctResultInfo;
import net.icarplus.car.bean.CertInfo;
import net.icarplus.car.constant.Content;
import net.icarplus.car.constant.UrlValues;
import net.icarplus.car.manager.BaseActivity;
import net.icarplus.car.tools.DateUtils;
import net.icarplus.car.tools.HttpService;
import net.icarplus.car.tools.ImageCacheManager;
import net.icarplus.car.tools.S;
import net.icarplus.car.tools.SPUtils;
import net.icarplus.car.tools.T;
import net.icarplus.car.tools.ToolBarHelper;
import net.icarplus.car.tools.Utils;

import org.json.JSONArray;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 项目名称：icarplus-car-android
 * 类描述：
 * 创建人：Gophy
 * 创建时间：16/3/11 12:55
 * 修改人：Gophy
 * 修改时间：16/3/11 12:55
 * 修改备注：
 */
public class CertificateUploadActivity extends BaseActivity implements View.OnClickListener {
    private Toolbar toolbar;
    private PopupWindow idPopupWindow;

    private ImageView idUpImgv, idDownImagv, idDriveImagv, idExampleImagv;
    private TextView photosTxt, takePhotoTxt, certStatusTxt;


    private int IDUP = 1, IDDOWN = 2, IDDRIVE = 3, currentId;

    private String pathIdUp, pathIdDown, pathIdDrive;

    private Button submitBtn;

    private EditText idEdit, nameEdit;

    private RelativeLayout certificate_id_up_relayout;
    private RelativeLayout certificate_id_down_relayout;
    private RelativeLayout certificate_id_drive_relayout;

    private List<CertInfo> saveCertInfoList = null;

    private int btnType = 0;//拍照或者从本地取图片
    private final int typePhotosTxt = 1;
    private final int typeTakePhotoTxt = 2;

    private JSONArray arrayLists;

    private LinearLayout certStatusLilayout;

    @Override
    public void setContent() {
        setContentView(R.layout.activity_certificate_upload);
    }

    @Override
    public void initComponent() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        ToolBarHelper.setNormalTitleAndBack(this, toolbar, getString(R.string.my_certificate_info));

        certificate_id_up_relayout = (RelativeLayout) findViewById(R.id.certificate_id_up_relayout);
        certificate_id_down_relayout = (RelativeLayout) findViewById(R.id.certificate_id_down_relayout);
        certificate_id_drive_relayout = (RelativeLayout) findViewById(R.id.certificate_id_drive_relayout);

        idUpImgv = (ImageView) findViewById(R.id.certificate_id_up_imgv);
        idDownImagv = (ImageView) findViewById(R.id.certificate_id_down_imgv);
        idDriveImagv = (ImageView) findViewById(R.id.certificate_id_drive_imgv);

        submitBtn = (Button) findViewById(R.id.certificate_submit_btn);
        idEdit = (EditText) findViewById(R.id.certificate_id_edit);
        nameEdit = (EditText) findViewById(R.id.certificate_name_edit);
        certStatusTxt = (TextView)findViewById(R.id.certificate_cert_status_txt);
        certStatusLilayout = (LinearLayout)findViewById(R.id.certificate_cert_status_lilayout);
    }

    @Override
    public void setListener() {
        certificate_id_up_relayout.setOnClickListener(this);
        certificate_id_down_relayout.setOnClickListener(this);
        certificate_id_drive_relayout.setOnClickListener(this);
        submitBtn.setOnClickListener(this);
    }

    @Override
    public void onAfterInit() {
        System.out.println("ddddd:" + MyApplication.acctResultInfo);

        if(MyApplication.acctResultInfo!=null){
            refreshUI(MyApplication.acctResultInfo);
        }

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.certificate_id_up_relayout:
                currentId = IDUP;
                openPopupWindow();
                break;
            case R.id.certificate_id_down_relayout:
                currentId = IDDOWN;
                openPopupWindow();
                break;
            case R.id.certificate_id_drive_relayout:
                currentId = IDDRIVE;
                openPopupWindow();
                break;
            case R.id.pupwindow_photos_txt:
                btnType = typePhotosTxt;
                Intent it = new Intent(Intent.ACTION_PICK, null);
                it.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(it, 1);
                idPopupWindow.dismiss();
                break;
            case R.id.certificate_submit_btn:
                if (isAllWrite()) {
                    certificateSubmit();
                }
                break;
            case R.id.pupwindow_take_photo_txt:
                btnType = typeTakePhotoTxt;
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, 1);
                idPopupWindow.dismiss();
                break;
            default:
                break;
        }
    }


    private void certificateSubmit() {
        Map<String, Object> param = new HashMap<String, Object>();
        String name = "";
        param.put("mobile", SPUtils.getString(this,"LoginInfo",null));
        name = Utils.getAsciiString(nameEdit.getText().toString());
        param.put("custName", name);

        Map<String, Object> cerParams = new HashMap<String, Object>();


        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        if (!S.isEmpty(pathIdUp)) {
            HashMap<String, String> idUpMap = new HashMap<String, String>();
            idUpMap.put("certTypeCode", "0101"); //身份证正面
            idUpMap.put("certNo", idEdit.getText().toString());
            idUpMap.put("certName", name);
            list.add(idUpMap);
        }
        if (!S.isEmpty(pathIdDown)) {
            HashMap<String, String> idDowmMap = new HashMap<String, String>();
            idDowmMap.put("certTypeCode", "0102"); //身份证反面
            idDowmMap.put("certNo", idEdit.getText().toString());
            idDowmMap.put("certName", name);
            list.add(idDowmMap);
        }

        if (!S.isEmpty(pathIdDrive)) {
            HashMap<String, String> idDriveMap = new HashMap<String, String>();
            idDriveMap.put("certTypeCode", "02"); //驾驶证
            idDriveMap.put("certNo", idEdit.getText().toString());
            idDriveMap.put("certName", name);
            list.add(idDriveMap);
        }
        param.put("certList", list);

        Map<String, String> fileParam = new HashMap<String, String>();
        if (!S.isEmpty(pathIdUp)) {
            fileParam.put("fileData0101", pathIdUp);
        }
        if (!S.isEmpty(pathIdDown)) {
            fileParam.put("fileData0102", pathIdDown);
        }
        if (!S.isEmpty(pathIdDrive)) {
            fileParam.put("fileData02", pathIdDrive);
        }
        upLoadFile(UrlValues.CERTIFICATE_UPLOAD_URL, param, fileParam, handler);

//        File file = new File(pathIdUp);
//        File file2 = new File(pathIdDown);
//        File file3 = new File(pathIdDrive);
//        if (!file.exists() || !file2.exists() || !file3.exists()) {
//            Toast.makeText(CertificateUploadActivity.this, "文件不存在，请修改文件路径", Toast.LENGTH_SHORT).show();
//            return;
//        }

//        OkHttpUtils.post()
//                .addFile("fileData0101", pathIdUp, file)
//                .addFile("fileData0102", pathIdDown, file2)
//                .addFile("fileData02", pathIdDrive, file3)
//                .url(UrlValues.CERTIFICATE_UPLOAD_URL)
//                .params(param)
//                .build()
//                .execute(new StringCallback() {
//                    @Override
//                    public void onError(Call call, Exception e) {
//                    }
//
//                    @Override
//                    public void onResponse(String response) {
//
//
//                    }
//                });
//


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (data != null) {
                    if (btnType == typePhotosTxt) {
                        cutPhoto(data.getData());// 裁剪图片
                    } else if (btnType == typeTakePhotoTxt) {
                        setTakePhoto(data);
                    }
                }
                break;
            case 2:
                //裁剪完返回结果
                if (data != null) {
                    Bundle extras = data.getExtras();
                    Bitmap bm = extras.getParcelable("data");
                    String path = Content.SDCARDIMAGEUPLOADCACHE + DateUtils.getVideoDate() + ".png";
                    if (bm != null) {
                        ImageCacheManager.saveBitmap(path, bm, 100);
                        if (currentId == IDUP) {
                            pathIdUp = path;
                            idUpImgv.setBackgroundDrawable(null);
                            idUpImgv.setImageBitmap(bm);
                        } else if (currentId == IDDOWN) {
                            pathIdDown = path;
                            idDownImagv.setBackgroundDrawable(null);
                            idDownImagv.setImageBitmap(bm);
                        } else {
                            pathIdDrive = path;
                            idDriveImagv.setBackgroundDrawable(null);
                            idDriveImagv.setImageBitmap(bm);
                        }
                    }
                }
                break;
            case 3:
                break;
            default:
                break;
        }
    }

    private TextView ts;
    private LinearLayout phone_select;

    private void openPopupWindow() {
        if (idPopupWindow == null) {
            View popupLayout = getLayoutInflater().inflate(R.layout.popupwindow_id, null);
            phone_select = (LinearLayout) popupLayout.findViewById(R.id.phone_select);
            photosTxt = (TextView) popupLayout.findViewById(R.id.pupwindow_photos_txt);
            takePhotoTxt = (TextView) popupLayout.findViewById(R.id.pupwindow_take_photo_txt);
            idExampleImagv = (ImageView) popupLayout.findViewById(R.id.pupwindow_id_example_imgv);
            ts = (TextView) popupLayout.findViewById(R.id.ts);
            idPopupWindow = new PopupWindow(popupLayout, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
            idPopupWindow.setFocusable(true);
            idPopupWindow.setBackgroundDrawable(new BitmapDrawable());
            //防止虚拟软键盘被弹出菜单遮住
            idPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
            //设置PopupWindow的弹出和消失效果
            idPopupWindow.setAnimationStyle(R.style.AnimBottom);
            idPopupWindow.showAtLocation(findViewById(R.id.certificate_lilayout), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
            popupLayout.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    // TODO Auto-generated method stub
                    idPopupWindow.dismiss();
                    return true;
                }
            });
            photosTxt.setOnClickListener(this);
            takePhotoTxt.setOnClickListener(this);
        } else {
            idPopupWindow.showAtLocation(findViewById(R.id.certificate_lilayout), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        }
        if (isCheckCeritificate) {
            phone_select.setVisibility(View.GONE);
        } else {
            phone_select.setVisibility(View.VISIBLE);
        }

        if (currentId == IDUP) {
            if (isHaveUpImv) {
                ts.setVisibility(View.GONE);
                ViewGroup.LayoutParams layoutParams = idExampleImagv.getLayoutParams();
                layoutParams.width = RelativeLayout.LayoutParams.MATCH_PARENT;
                layoutParams.height = 400;
                idExampleImagv.setScaleType(ImageView.ScaleType.FIT_XY);
                for (int i = 0; saveCertInfoList != null && i < saveCertInfoList.size(); i++) {
                    CertInfo certInfo = saveCertInfoList.get(i);
                    if (certInfo != null) {
//                        String url = Content.URLDOWNLOADIMAGE + certInfo.getCertImgUrl() + "&" + certInfo.getFileName();
//                        if ("0101".equals(certInfo.getCertTypeCode())) {//身份证正面
//                            ImageUtil.asyncImageLoad(idExampleImagv, url, Content.SDCARDIMAGE, null);
//                        }
                    }
                }
            } else {
                idExampleImagv.setImageDrawable(null);
                ts.setVisibility(View.VISIBLE);
                ViewGroup.LayoutParams layoutParams = idExampleImagv.getLayoutParams();
                layoutParams.width = RelativeLayout.LayoutParams.WRAP_CONTENT;
                layoutParams.height = RelativeLayout.LayoutParams.WRAP_CONTENT;
                idExampleImagv.setBackgroundResource(R.mipmap.id_front);
            }
        } else if (currentId == IDDOWN) {
            if (isHaveDownImv) {
                ts.setVisibility(View.GONE);
                idExampleImagv.setScaleType(ImageView.ScaleType.FIT_XY);
                ViewGroup.LayoutParams layoutParams = idExampleImagv.getLayoutParams();
                layoutParams.width = RelativeLayout.LayoutParams.MATCH_PARENT;
                layoutParams.height = 400;
                for (int i = 0; saveCertInfoList != null && i < saveCertInfoList.size(); i++) {
                    CertInfo certInfo = saveCertInfoList.get(i);
                    if (certInfo != null) {
//                        String url = Content.URLDOWNLOADIMAGE + certInfo.getCertImgUrl() + "&" + certInfo.getFileName();
//                        LogUtil.e("url:" + url);
//                        if ("0102".equals(certInfo.getCertTypeCode())) {
//                            ImageUtil.asyncImageLoad(idExampleImagv, url, Content.SDCARDIMAGE, null);
//                        }
                    }
                }
            } else {
                idExampleImagv.setImageDrawable(null);
                ts.setVisibility(View.VISIBLE);
                ViewGroup.LayoutParams layoutParams = idExampleImagv.getLayoutParams();
                layoutParams.width = RelativeLayout.LayoutParams.WRAP_CONTENT;
                layoutParams.height = RelativeLayout.LayoutParams.WRAP_CONTENT;
                idExampleImagv.setBackgroundResource(R.mipmap.id_back);
            }
        } else {
            if (isHaveDriverImv) {
                ts.setVisibility(View.GONE);
                idExampleImagv.setScaleType(ImageView.ScaleType.FIT_XY);
                ViewGroup.LayoutParams layoutParams = idExampleImagv.getLayoutParams();
                layoutParams.width = RelativeLayout.LayoutParams.MATCH_PARENT;
                layoutParams.height = 400;
                for (int i = 0; saveCertInfoList != null && i < saveCertInfoList.size(); i++) {
                    CertInfo certInfo = saveCertInfoList.get(i);
                    if (certInfo != null) {
//                        String url = Content.URLDOWNLOADIMAGE + certInfo.getCertImgUrl() + "&" + certInfo.getFileName();
//                        LogUtil.e("url:" + url);
//                        if ("02".equals(certInfo.getCertTypeCode())) {
//                            ImageUtil.asyncImageLoad(idExampleImagv, url, Content.SDCARDIMAGE, null);
//                        }
                    }
                }
            } else {
                idExampleImagv.setImageDrawable(null);
                ts.setVisibility(View.VISIBLE);
                ViewGroup.LayoutParams layoutParams = idExampleImagv.getLayoutParams();
                layoutParams.width = RelativeLayout.LayoutParams.WRAP_CONTENT;
                layoutParams.height = RelativeLayout.LayoutParams.WRAP_CONTENT;
                idExampleImagv.setBackgroundResource(R.mipmap.driver_front);
            }
        }
    }

    public void cutPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "false");
//		// aspectX aspectY 是宽高的比例
//		intent.putExtra("aspectX", 1);
//		intent.putExtra("aspectY", 1);
//		// outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 2);
    }


    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0:
                    break;
                case 1:
                    String errormsg = (String) msg.obj;
                    showAlerDialog("提示", errormsg, null);
                    break;
                case 1000:

                    Log.e("1000000", "11000100101");
                    AcctResultInfo resultInfo = (AcctResultInfo)msg.obj;
//                    refreshUI(resultInfo);
                    break;
                case 1001:
                    Log.e("10000001", "1111111111");
                    T.showShort("附件上传成功");
                    setResult(RESULT_OK);
                    finish_Activity();
                    break;
                case 30000:
                    String message = (String) msg.obj;
                    showAlerDialog("提示", "您好，服务器繁忙，请稍后继续！", null);
                    break;
                default:
                    break;
            }
        }
    };


    private boolean isHaveUpImv = false;
    private boolean isHaveDownImv = false;
    private boolean isHaveDriverImv = false;
    private boolean isCheckCeritificate = false;


    private void refreshUI(AcctResultInfo resultInfo) {

//        Utils.showToast(resultInfo.getReturnMsg());
        nameEdit.setText(resultInfo.custName);
        idEdit.setText(resultInfo.certNo);
        if(!"01".equals(resultInfo.rentCertStatus)) {
            certStatusLilayout.setVisibility(View.VISIBLE);
            if("02".equals(resultInfo.rentCertStatus)) {
                isCheckCeritificate = false;
                certStatusTxt.setText("待审核");
                changeSubmitBtnStatus(-1);
            }else if("03".equals(resultInfo.rentCertStatus)) {
                isCheckCeritificate = true;
                certStatusTxt.setText("审核通过");
                changeSubmitBtnStatus(-1);
            }else {
                isCheckCeritificate = false;
                certStatusTxt.setText("审核不通过");
                changeSubmitBtnStatus(1);
            }
        }
        if(MyApplication.acctResultInfo != null ) {

            List<CertInfo> list = resultInfo.queryList;
            saveCertInfoList = list;
            CertInfo certInfo = null;
            for(int i = 0; list != null && i < list.size(); i++) {
                certInfo = list.get(i);
                if(certInfo != null) {
                    String url = UrlValues.CAR_IMG_ID + certInfo.getCertImgUrl()  + "&"+ certInfo.getFileName();
                    Log.e("url:" ,url);
                    if("0101".equals(certInfo.getCertTypeCode())) {//身份证正面
                        isHaveUpImv = true;
                        ImageCacheManager.setImageBackgroundToImageView(this,
                                idUpImgv, url, R.mipmap.logo);
                    }else if("0102".equals(certInfo.getCertTypeCode())) {//身份证反面
                        isHaveDownImv = true;
                        ImageCacheManager.setImageBackgroundToImageView(this,
                                idDownImagv, url, R.mipmap.logo);
                    }else if("02".equals(certInfo.getCertTypeCode())) {//驾驶证
                        isHaveDriverImv = true;
                        ImageCacheManager.setImageBackgroundToImageView(this,
                                idDriveImagv, url, R.mipmap.logo);
                    }

                }
            }
        }
    };

    public void setTakePhoto(Intent data) {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
            Toast.makeText(CertificateUploadActivity.this, "SD卡不可用", Toast.LENGTH_SHORT).show();
            return;
        }
        Bundle bundle = data.getExtras();
        if (bundle == null) {
            return;
        }
        Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式
        FileOutputStream b = null;
        String xc = Environment.getExternalStorageDirectory() + File.separator + "DCIM" + File.separator + "Camera" + File.separator;//默认相册
        File file = new File(xc);
//		File file = new File(Content.SDCARDIMAGE);
        file.mkdirs();// 创建文件夹
        String path = xc + "IMG" + DateUtils.getVideoDate() + ".png";
//		String path = Content.SDCARDIMAGE + Utils.getVideoDate()+  ".png";
        Log.e("Long", "位置：" + path);
        String fileName = path;
        try {
            b = new FileOutputStream(fileName);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, b);// 把数据写入文件
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                b.flush();
                b.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (currentId == IDUP) {
            pathIdUp = path;
            idUpImgv.setImageBitmap(bitmap);
        } else if (currentId == IDDOWN) {
            pathIdDown = path;
            idDownImagv.setImageBitmap(bitmap);
        } else {
            pathIdDrive = path;
            idDriveImagv.setImageBitmap(bitmap);
        }
    }

    private boolean pathIsNotNull(String value) {
        if (value == null) {
            return false;
        }
        if (value.equals("")) {
            return false;
        }
        return true;
    }


    public boolean isAllWrite() {

        if (!pathIsNotNull(pathIdUp) || !pathIsNotNull(pathIdDown) || !pathIsNotNull(pathIdDrive)) {
            showAlerDialog("提示", "请选择上传身份证正面、反面和驾驶证图片", null);
            return false;
        }
        return true;
    }

    private byte[] image2byte(String path) {
        byte[] data = null;
        FileInputStream input = null;
        try {
            input = new FileInputStream(new File(path));
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int numBytesRead = 0;
            while ((numBytesRead = input.read(buf)) != -1) {
                output.write(buf, 0, numBytesRead);
            }
            data = output.toByteArray();
            output.close();
            input.close();
        } catch (FileNotFoundException ex1) {
            ex1.printStackTrace();
        } catch (IOException ex1) {
            ex1.printStackTrace();
        }
        return data;
    }
    private void upLoadFile(final String url, final Map<String, Object> param, final Map<String, String> fileParam, final Handler handler) {

        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                try {
                    Log.e("参数：", param.toString());
                    String result = HttpService.HttpsPostData(url, param, fileParam);
                    if (result != null && result.indexOf("10000") != -1) {
                        handler.obtainMessage(1001, result).sendToTarget();
                        Log.e("Long", "kkk:" + result);
//						handler.sendEmptyMessage(1001);
                    } else {
                        handler.obtainMessage(30000, "上传失败").sendToTarget();
                    }
                } catch (Exception e) {
                    Log.e("Exception:::::", e.toString());
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    handler.obtainMessage(30000, "上传失败").sendToTarget();
                }
            }
        }).start();
    }
    @SuppressWarnings("ResourceType")
    public void changeSubmitBtnStatus(int status) {
        if(status == -1) {
            submitBtn.setBackgroundColor(R.color.gray);
            submitBtn.setClickable(false);
            nameEdit.setEnabled(false);
            idEdit.setEnabled(false);
        }else {
            submitBtn.setBackgroundResource(R.drawable.btn_yellow_xml);
            submitBtn.setClickable(true);
            nameEdit.setEnabled(true);
            idEdit.setEnabled(true);
        }
    }

}